<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Money;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Student extends AdminBase
{
    protected $student_model;
    protected $classes_model;
    protected $money_model;

    public function __construct()
    {
        parent::__construct();
        $this->student_model = new \app\common\model\Student();
        $this->classes_model = new \app\common\model\Classes();
        $this->money_model = new Money();
    }

    /**
     * 学生列表
     * @param $class_id
     * @param $name
     * @param $page
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($class_id = 0,$name = '', $page = 1)
    {
        $map = [];

        if ($class_id > 0) {
            $map['class_id'] = $class_id;
        }

        if (!empty($name)) {
            $map['name'] = ['like', "%{$name}%"];
        }

        $class_list = $this->classes_model->all();

        $student_list = $this->student_model->where($map)->order('id DESC')
            ->paginate(10, false, ['page' => $page])->each(function($item, $key){
                $class_id = $item['class_id'];
                $class = $this->classes_model->find($class_id);
                $item['class_name'] = $class['class_name'];
            });
        return $this->fetch('index', [
            'student_list' => $student_list,
            'class_list' => $class_list,
            'class_id' => $class_id,
            'name' => $name
        ]);
    }

    /**
     * Excel导出
     * @param $class_id
     * @param $name
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function excel($class_id = 0,$name = '')
    {
        $map = [];

        if ($class_id > 0) {
            $map['class_id'] = $class_id;
        }

        if (!empty($name)) {
            $map['name'] = ['like', "%{$name}%"];
        }

        $student_list = $this->student_model->where($map)->order('id DESC')
            ->paginate(10000)->each(function ($item, $key){
            $class_id = $item['class_id'];
            $class = $this->classes_model->find($class_id);
            $item['class_name'] = $class['class_name'];
        });

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 设置表头
        $headers = ['ID', '姓名', '手机', '邮箱', '身份证', '班级', '备注', '创建时间', '更新时间'];
        $col = 'A';
        foreach ($headers as $index => $header) {
            $sheet->setCellValue($col . '1', $header);
            $col++;
        }

        // 填充数据
        $row = 2;
        foreach ($student_list as $student) {
            $sheet->setCellValue('A' . $row, $student['id']);
            $sheet->setCellValue('B' . $row, $student['name']);
            $sheet->setCellValue('C' . $row, "'".$student['phone']."'");
            $sheet->setCellValue('D' . $row, $student['email']);
            $sheet->setCellValue('E' . $row, "'" . $student['id_card']."'");
            $sheet->setCellValue('F' . $row, $student['class_name']);
            $sheet->setCellValue('G' . $row, $student['remark']);
            $sheet->setCellValue('H' . $row, $student['create_time']);
            $sheet->setCellValue('I' . $row, $student['update_time']);
            $row++;
        }

        // 输出
        $filename = '学生信息导出_' . date('YmdHis') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }

    /**
     * 添加学生
     * @return mixed|void
     * @throws \think\exception\DbException
     */
    public function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($data['class_id'] == 0) {
                unset($data['class_id']);
            }
            $result_validate = $this->validate($data, 'Student');
            if ($result_validate !== true) {
                $this->error($result_validate);
            } else {
                $result = $this->student_model->allowField(true)->save($data);
                if ($result) {
                    $money = [
                        'student_id' => $this->student_model->id,
                        'prac_amount' => 0,
                        'status' => 0,
                    ];
                    $this->money_model->allowField(true)->isUpdate(false)->save($money);
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        } else {
            $class_list = $this->classes_model->all();
            return $this->fetch('add',['class_list' => $class_list]);
        }
    }

    /**
     * 编辑学生
     * @param $id
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id = 0){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $result_validate = $this->validate($data, 'Student');
            if ($result_validate !== true) {
                $this->error($result_validate);
            } else {
                $result = $this->student_model->allowField(true)->save($data, ['id' => $id]);
                if ($result !== false) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        } else {
            $student = $this->student_model->find($id);
            $class_list = $this->classes_model->all();
            return $this->fetch('edit',['student' => $student,'class_list' => $class_list]);
        }
    }

    /**
     * 删除学生
     * @param $id
     * @return void
     */
    public function delete($id = 0)
    {
        if ($id === 0) {
            $this->error("删除失败！err-1");
        } else {
            $result = $this->student_model->destroy($id);
            if ($result) {
                $this->success("删除成功");
            } else {
                $this->success("删除失败！err-2");
            }
        }
    }
}